package kr.hkit.androidcomplete02.XMLparser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kr.hkit.androidcomplete02.R;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class Sax_parserAcitivity extends Activity {
	
	private ListView list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		
		new ParsingXML().execute("order.xml");
		
	}
	
	private class ParsingXML extends AsyncTask<String, Void, ArrayList<Item>> {
		private ProgressDialog progressDlg;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDlg = ProgressDialog.show(Sax_parserAcitivity.this, "Wait", "xml parsing...");
		}
		
		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			super.onPostExecute(result);
			MyAdapter adapter = new MyAdapter(Sax_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
			
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine())!=null){
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		//SAX parser
		private ArrayList<Item> parsingXml(String xml) {
			
			
			final ArrayList<Item> arItem = new ArrayList<Item>();
			
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser;
			
			try {
				parser = factory.newSAXParser();
				XMLReader reader = parser.getXMLReader();
			
				reader.setContentHandler(new DefaultHandler(){
					boolean initItem = false;
					Item itemClass;

				@Override //문서 처음 시작시 호출
				public void startDocument() throws SAXException {
					super.startDocument();
					Log.d("SAX", "startDocument()");
				}

				@Override
				public void endDocument() throws SAXException {
					super.endDocument();
					Log.d("SAX", "endDocument()");
				}

				@Override
				public void startElement(String uri, String localName, String qName, 
						Attributes attributes)
						throws SAXException {
					String str = "uri : " + uri + " localName : " + localName + " qName : " + qName 
							+ " Attributes : " + attributes;
					Log.d("SAX", "startElement()" +str);
					super.startElement(uri, localName, qName, attributes);
					
					if(localName.equalsIgnoreCase("item")){ //order은 필요없으니까 
						initItem = true; //한줄읽고 밑에줄 읽을때 새로 생성해야되니까 구분주기 위해서
						itemClass = new Item();
					}
					
					if(attributes.getLength()>0){ //프라이스 메이커 속성담기
						for(int i=0; i<attributes.getLength(); i++){
							if (attributes.getLocalName(i).equalsIgnoreCase("price")){
								itemClass.setItemPrice(Integer.parseInt(attributes.getValue(i)));
							}else{
								itemClass.setMakerName(attributes.getValue(i));
							}
						}
					}
				}

				@Override
				public void endElement(String uri, String localName,
						String qName) throws SAXException {
					String str = "uri : " + uri + " localName : " + localName + " qName : " + qName; 
					Log.d("SAX", "endElement()" + str);
					super.endElement(uri, localName, qName);
				}

				@Override //Mouse앞에 커서 왔을때. mouse같은게 characters
				public void characters(char[] ch, int start, int length)
						throws SAXException {
					String str = "ch : " + ch.toString() + " start: " + start + " length : " + length;
					Log.d("SAX", "characters()" + str);
					
					super.characters(ch, start, length);
					
					if(initItem){
						itemClass.setItemName(new String(ch,start,length));
						arItem.add(itemClass);
						initItem = false;
					}
				}
			});
				
				//파일 읽은거 넘겨주어야함
				InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
				reader.parse(new InputSource(is));
				
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return arItem;
		}
	}
}
